﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;

public partial class Expert_CompanyYiJia : System.Web.UI.Page
{
    private const int SpPrice = 10;
    private const int YiJiaPackPrice01 = 11;
    private const int YiJiaPackPrice1 = 12;
    private const int YiJiaPackPrice02 = 13;
    private const int YiJiaPackPrice2 = 14;
    //private const int YiJiaPackPrice03 = 15;
    //private const int YiJiaPackPrice3 = 15;
    private const int ExpertIdea = 15;
    private const int ExpertPrice1 = 16;
    private const int ExpertPrice2 = 17;
    private const int Accept_Company0 = 18;
    private const int Accept_Company = 19;
    private const int bidid = 20;
    private const int Submit = 21;
    private const int YiJiaBidPrice = 22;

    public string _strNone = "block";
    string _strProjectId = "";
    string _strUserType = "";
    string _project = "";
    int YiJiaSwitch = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        _project = Request.QueryString["projectid"];
        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        //_AccountType.Add(HZ.MBSM.DAL.AccountType.enumZMedicineCompany);
        //_AccountType.Add(HZ.MBSM.DAL.AccountType.enumHMedicineCompany);
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {
            ErrorMsg.Text = "";
            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            if (_Account.Sort == "1")
            {
                txtCompanyNameSC.Enabled = false;
            }

            if (!IsPostBack)
            {


            }
            string sql = "select top 1 YiJiaSwitch from dbo.V_Bargaining";
            Db che = new Db();
            DataTable tb = new DataTable();
            tb = che.DataTable(sql);
            if (tb.Rows.Count > 0)
            {
                YiJiaSwitch = int.Parse(tb.Rows[0].ItemArray[0].ToString());
                if (YiJiaSwitch == 0)
                {
                    Response.Write("<script>window.alert('限价开关没开！');window.close();</script>");

                    return;
                }
            }
            che.Close();
            _strProjectId = _project;
            //查询
            showGridView();
            //绑定字段
            RowDataBound();
            ////判断提交状态,来觉得提交按钮是否显示

            SelectSubmit();
            if (_Account != null)
            {
                _strUserType = SysFun.ToTrim(_Account.Type);
                //将建限价提交给投标人
                if (Request.Form["SaveCPrice"] == "提 交")
                {
                    UpdateSubmit();
                }
                if (Request.Form["PrintPrice"] == "打印")
                {
                    PrintCompanyPrice();
                }

            }
        }

    }

    public void showGridView()
    {
        getTrue();
        RowDataBound();
        string _strConditions = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "V_Bargaining";                                               //要查询的表明
        dbPage.Key = "Bidid";                                               //表的主键    
        dbPage.Where = _strConditions;                                           //查询条件    
        dbPage.SelectField = " bidid,GoodsId, ProductCode, ProductName, Medicinemodel, Outlookc, Factor,  case qualitylevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " END as qualitylevels, CompanyName_sc, "
            + "UserCode_sc, CompanyName_TB, UserCode_TB, SPPrice, LimitPrice*factor as LimitPrice, ExpertPrice1, YiJiaPackPrice1,YiJiaPackPrice2, ExpertPrice2, Accept_Company, Submit,CompanyIdea,ExpertIdea,YiJiaBidPrice  ";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页                 
        if (Request.Form["PrintPrice"] == "打印")
        {
            dbPage.PageSize = 1;                                                    //没有显示记录条数   
        }
        else
        {
            dbPage.PageSize = 10;                                                    //没有显示记录条数   
        }
        dbPage.OrderBy = "ProductCode,qualitylevels,GoodsId,Bidid";                  //排序字段
        System.Data.IDataReader dr = dbPage.ExecuteReader();
        GridView2.DataSource = dr;
        GridView2.DataBind();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键 

    }
    /// <summary>
    /// 拼接查询条件
    /// </summary>
    /// <returns></returns>
    public string fctConditions()
    {
        string _strWhere;
        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
        if (_Account != null)
        {
            _strProjectId = _project;

            //  _strWhere = "  ProjectId=" + _strProjectId + "  And checkstatus=1 and isbid = '0'";
            _strWhere = "  ProjectId=" + _strProjectId + "  And checkstatus=1 and isbid = '0' and accountid_tb=" + _Account.AccountId + " and";

            //药品通用名

            string _strProductName = SysFun.ToTrim(txtProductName.Text);
            if (_strProductName != "")
            {
                _strWhere += " ProductName like '%" + _strProductName + "%' And";
            }
            //品目号

            string _strProductCode = SysFun.ToTrim(txtProductCode.Text);
            if (_strProductCode != "")
            {
                _strWhere += " ProductCode = '" + _strProductCode + "' and";
            }
            //药品流水号

            string _strGoodsid = txtGoodsId.Text.Trim();
            if (_strGoodsid != "")
            {
                _strWhere += " Goodsid ='" + _strGoodsid + "' And";
            }

            //生产企业名称
            string _strCompanyNameSC = txtCompanyNameSC.Text.Trim();
            if (_strCompanyNameSC != "")
            {
                _strWhere += " CompanyName_sc like '%" + _strCompanyNameSC + "%' And";
            }
            //限价限价报价
            string _strAcceptCompany = lstAcceptCompany.SelectedValue;
            switch (_strAcceptCompany)//第一次的
            {
                case "全部":
                    break;
                case "企业已接受专家建限价":
                    //未接受已报价
                    _strWhere += " (Accept_Company=1 OR Accept_Company=2)  And";
                    break;
                case "未接受未报价":
                    _strWhere += " (accept_company=0 or accept_company is null) and (YiJiaPackPrice1=0 or YiJiaPackPrice1 is null)  And";
                    break;
                case "未接受已报价":
                    _strWhere += " YiJiaPackPrice1>0 and  (accept_company=0 or accept_company is null) And";
                    break;
            }
            if (YiJiaSwitch == 2)
                _strWhere += " isbid = 0  And";
            if (YiJiaSwitch == 3)
                _strWhere += " isbid = 0 and ExpertPrice1 > 0  And";
            if (_strWhere != "")
            {
                _strWhere = "  " + _strWhere.Substring(0, _strWhere.Length - 3);
            }
        }
        else
        {
            _strWhere = "";

        }
        return _strWhere;
    }

    private void RowDataBound()
    {
        foreach (GridViewRow row in GridView2.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {

                switch (getSubmit())
                {
                    case "0"://

                        break;
                    case "1"://            
                        row.Cells[YiJiaPackPrice01].Text = "<input style='width: 60px' type=text name='txtprice1" + row.Cells[bidid].Text + "' value=\"" + SysFun.ToDec(row.Cells[YiJiaPackPrice1].Text) + "\" /> ";
                        break;
                    case "2":

                        row.Cells[YiJiaPackPrice02].Text = "<input style='width: 60px' type=text name='txtprice2" + row.Cells[bidid].Text + "' value=\"" + SysFun.ToDec(row.Cells[YiJiaPackPrice2].Text) + "\" /> ";

                        break;
                    //case "3":

                    //    row.Cells[YiJiaPackPrice03].Text = "<input style='width: 60px' type=text name='txtprice3" + row.Cells[bidid].Text + "' value=\"" + SysFun.ToDec(row.Cells[YiJiaPackPrice3].Text) + "\" /> ";

                    //    break;




                }

                if (row.Cells[Accept_Company].Text == "1")
                {
                    if (Request.Form["PrintPrice"] == "打印")
                    {
                        row.Cells[Accept_Company0].Text = "是";
                    }
                    else
                    {
                        row.Cells[Accept_Company0].Text = "<input type=radio name ='radBid" + row.Cells[0].Text + "' value='1' checked>是<input type=radio name ='radBid" + row.Cells[0].Text + "' value='0'>否";
                    }
                }
                else
                {
                    if (Request.Form["PrintPrice"] == "打印")
                    {
                        row.Cells[Accept_Company0].Text = "否";
                    }
                    else
                    {
                        row.Cells[Accept_Company0].Text = "<input type='radio' name ='radBid" + row.Cells[0].Text + "' value='1'>是<input type=radio name ='radBid" + row.Cells[0].Text + "' value='0' checked>否";
                    }

                }
                row.Cells[0].Text = "<input  type='hidden' name='GoodsId' value='" + row.Cells[0].Text + "'>" + row.Cells[0].Text.ToString() + "";
            }
        }
    }
    /// <summary>
    /// 判断当前的提交状态,
    /// 默认为                  0     
    ///企业第一次限价,提交为    1     
    ///企业第二次限价 提交为    2     
    ///企业第三次限价,提交为    3     
    ///企业是否接受专家建限价   4
    ///</summary>
    private void SelectSubmit()
    {
        getTrue();
        switch (getSubmit())
        {
            case "1":
                GridView2.Columns[YiJiaPackPrice1].Visible = false;
                GridView2.Columns[YiJiaPackPrice02].Visible = false;
                //GridView2.Columns[YiJiaPackPrice03].Visible = false;
                GridView2.Columns[YiJiaPackPrice2].Visible = false;
                //GridView2.Columns[YiJiaPackPrice3].Visible = false;
                GridView2.Columns[ExpertIdea].Visible = false;
                GridView2.Columns[ExpertPrice1].Visible = true;
                GridView2.Columns[Accept_Company0].Visible = true;
                GridView2.Columns[Accept_Company].Visible = false;
                GridView2.Columns[YiJiaBidPrice].Visible = false;
                GridView2.Columns[YiJiaPackPrice01].Visible = true;
                _strNone = "none";
                Label1.Text = "<input name=\"SaveCPrice\" type=\"submit\" value=\"提 交\" class=\"button_bg8\" style=\"width: 120px; height: 18px;\" onclick=\"javascript:return CheckForm()\" id=\"Submit1\"  /> ";
                Label2.Text = "请给出第二次报价，报价时间2009年8月31至2009年9月1号。超时未报原报价为默认价！";
                break;
            case "2":
                GridView2.Columns[YiJiaPackPrice01].Visible = false;
                //GridView2.Columns[YiJiaPackPrice03].Visible = false;
                GridView2.Columns[YiJiaPackPrice2].Visible = false;
                //GridView2.Columns[YiJiaPackPrice3].Visible = false;
                GridView2.Columns[ExpertIdea].Visible = false;
                GridView2.Columns[ExpertPrice1].Visible = true;
                GridView2.Columns[ExpertPrice2].Visible = true;
                GridView2.Columns[Accept_Company0].Visible = true;
                GridView2.Columns[Accept_Company].Visible = false;
                GridView2.Columns[YiJiaBidPrice].Visible = false;
                GridView2.Columns[YiJiaPackPrice1].Visible = true;
                GridView2.Columns[YiJiaPackPrice02].Visible = true;
                Label2.Text = "请给出第三次报价，报价时间2009年8月31至2009年9月1号。超时未报原报价为默认价！";
                Label1.Text = "<input name=\"SaveCPrice\" type=\"submit\" value=\"提 交\" class=\"button_bg8\" style=\"width: 120px; height: 18px;\" onclick=\"javascript:return CheckForm()\" id=\"Submit1\"  /> ";
                _strNone = "block";
                break;
            //case "3":
            //    GridView2.Columns[YiJiaPackPrice02].Visible = false;
            //    GridView2.Columns[YiJiaPackPrice01].Visible = false;
            //    GridView2.Columns[YiJiaPackPrice3].Visible = false;
            //    GridView2.Columns[ExpertIdea].Visible = false;
            //    GridView2.Columns[ExpertPrice1].Visible = false;
            //    GridView2.Columns[Accept_Company0].Visible = false;
            //    GridView2.Columns[Accept_Company].Visible = false;
            //    GridView2.Columns[YiJiaBidPrice].Visible = false;
            //    GridView2.Columns[YiJiaPackPrice1].Visible = true;
            //    GridView2.Columns[YiJiaPackPrice2].Visible = true;
            //    GridView2.Columns[YiJiaPackPrice03].Visible = true;
            //    GridView2.Columns[YiJiaBidPrice].Visible = false;
            //    _strNone = "block";
            //    Label2.Text = "贵公司所报品种价格不符合我们确定的标底值，请给出第四次报价，报价时间2007年10月9至2007年10月20号。超时未报原报价为默认价！";
            //    Label1.Text = "<input name=\"SaveCPrice\" type=\"submit\" value=\" 提交报价 \" class=\"button_bg8\" style=\"width: 120px; height: 18px;\" onclick=\"javascript:return CheckForm()\" id=\"Submit1\"  /> ";
            //    break;
            case "3":
                GridView2.Columns[YiJiaPackPrice01].Visible = false;
                GridView2.Columns[YiJiaPackPrice02].Visible = false;
                //GridView2.Columns[YiJiaPackPrice03].Visible = false;
                GridView2.Columns[YiJiaPackPrice1].Visible = true;
                GridView2.Columns[YiJiaPackPrice2].Visible = true;
                //GridView2.Columns[YiJiaPackPrice3].Visible = true;
                GridView2.Columns[ExpertIdea].Visible = false;
                GridView2.Columns[ExpertPrice1].Visible = true;
                GridView2.Columns[Accept_Company0].Visible = true;
                GridView2.Columns[Accept_Company].Visible = true;
                GridView2.Columns[YiJiaBidPrice].Visible = false;
                GridView2.Columns[Accept_Company].Visible = false;
                Label1.Text = "<input name=\"PrintPrice\" type=\"submit\" value=\"打印\" class=\"button_bg8\" style=\"width: 120px; height: 18px;\" onclick=\"javascript:return CheckForm()\" id=\"Submit1\"  /> ";
                Label2.Text = "三次限价报价完成，是否接受专家建限价？";
                Label3.Visible = false;
                Button3.Visible = true;
                _strNone = "none";
                break;
        }

        GridView2.Columns[bidid].Visible = false;
        GridView2.Columns[Submit].Visible = false;
    }
    private void UpdateSubmit()
    {
        string strBid = "", strPrice = "", strSql = "";
        bool flag = false;
        Db db = new Db();
        if (GridView2.Rows.Count > 0)
        {
            //更新报价
            foreach (GridViewRow row in GridView2.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    strBid = "";
                    strBid = row.Cells[bidid].Text;
                    switch (getSubmit())
                    {
                        case "0":
                            break;
                        case "1":
                            strPrice = Request.Form["txtprice1" + row.Cells[bidid].Text];
                            if (checkFloat(strPrice) && Convert.ToDouble(strPrice) <= Convert.ToDouble(row.Cells[SpPrice].Text))
                                strSql = "update V_Bargaining set YiJiaPackPrice1 = " + strPrice + " where bidid = " + strBid;
                            else
                            {
                                //Response.Write("<script>window.alert('" + row.Cells[0].Text + "报价有问题！');</script>");
                                Response.Write("<script>window.alert('报价有问题，已经恢复为原价格！');</script>");
                                ErrorMsg.Text += "流水号：" + row.Cells[0].Text + "报价有问题！<BR />";
                            }
                            break;
                        case "2":
                            strPrice = Request.Form["txtprice2" + row.Cells[bidid].Text];
                            if (checkFloat(strPrice) && Convert.ToDouble(strPrice) <= Convert.ToDouble(row.Cells[YiJiaPackPrice1].Text))
                                strSql = "update V_Bargaining set YiJiaPackPrice2 = " + strPrice + " where bidid = " + strBid;
                            else
                            {
                                Response.Write("<script>window.alert('报价有问题，已经恢复为原价格！');</script>");
                                ErrorMsg.Text += "流水号：" + row.Cells[0].Text + "报价有问题！<BR />";
                            }
                            break;
                        //case "3":
                        //    strPrice = Request.Form["txtprice3" + row.Cells[bidid].Text];
                        //    if (checkFloat(strPrice) && Convert.ToDouble(strPrice) <= Convert.ToDouble(row.Cells[YiJiaPackPrice2].Text))
                        //        strSql = "update V_Bargaining set YiJiaPackPrice3 = " + strPrice + " where bidid = " + strBid;
                        //    break;
                        case "3":
                            break;
                    }
                    if (strSql != "")
                    {
                        try
                        {
                            db.Command(strSql);
                            flag = true;
                        }
                        catch (Exception ex)
                        {
                            flag = false;
                            return;
                        }
                    }
                }
            }

            if (flag)
                Response.Write("<script>window.alert('价格保存完成！');</script>");
            else
                Response.Write("<script>window.alert('价格保存有异常发生，请重新操作！');</script>");
        }
        else
        {
            Response.Write("<script>window.alert('没有要保存的药品价格！);</script>");
        }
        db.Close();
        //查询
        //查询
        showGridView();
        //绑定字段
        RowDataBound();
        ////判断提交状态,来觉得提交按钮是否显示

        SelectSubmit();
    }
    private bool checkFloat(string strValue)
    {
        double num = 0;
        bool falg = false;
        try
        {
            num = Convert.ToDouble(strValue.ToString());
            falg = true;
        }
        catch (Exception ex)
        {
            falg = false;
        }
        return falg;
    }
    public string GetWhereUserType(string strUserType)
    {
        string _strWhere = "";
        if (_strUserType == "12")
        {
            _strWhere += " ProductCode like 'Z%' ";
        }
        else
        {
            _strWhere += " ProductCode like 'H%' ";
        }
        return _strWhere;
    }
    protected void PrintCompanyPrice()
    {

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        // 添加头信息，为"文件下载/另存为"对话框指定默认文件名 
        // Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(accountid.ToString()) + ".xls");
        Response.AddHeader("Content-Disposition", "attachment; filename=11.xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentEncoding = System.Text.Encoding.UTF7;  //解决将gridview导出成excel时出现乱码  
        Response.ContentType = "application/ms-excel";
        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        this.GridView2.RenderControl(oHtmlTextWriter);
        System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
        strHtml.Append(oStringWriter.ToString().Substring(0, 197));
        strHtml.Append("<tr border=\"0\"><td colspan='15'align=\"center\"><strong><span style=\"font-size: 24pt\">限价品种投标人确认表</span></strong></td></tr>");
        strHtml.Append(oStringWriter.ToString().Substring(198, oStringWriter.ToString().Length - 215));
        strHtml.Append("<tr border=\"0\"><td colspan='3' align='right'><strong>投标人签字：</strong></td><td colspan='4'  style='width: 18px'></td><td  colspan='2' align='right'><strong>时间：</strong></td><td  colspan='6'align='left' >" + DateTime.Now.ToString() + "</td></tr>");

        strHtml.Append(oStringWriter.ToString().Substring(oStringWriter.ToString().Length - 16, 16));
        // 把文件流发送到客户端 
        Response.Write(strHtml.ToString());
        // 停止页面的执行

        Response.End();

    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //OverRide　为了使导出成Excel可行！

    }


    private void getTrue()
    {
        GridView2.Columns[YiJiaPackPrice01].Visible = true;
        GridView2.Columns[YiJiaPackPrice1].Visible = true;
        GridView2.Columns[YiJiaPackPrice02].Visible = true;
        GridView2.Columns[YiJiaPackPrice2].Visible = true;
        //GridView2.Columns[YiJiaPackPrice03].Visible = true;
        //GridView2.Columns[YiJiaPackPrice3].Visible = true;
        GridView2.Columns[ExpertIdea].Visible = true;
        GridView2.Columns[ExpertPrice1].Visible = true;
        GridView2.Columns[Accept_Company0].Visible = true;
        GridView2.Columns[Accept_Company].Visible = true;
        GridView2.Columns[bidid].Visible = true;
        GridView2.Columns[Submit].Visible = true;
        GridView2.Columns[YiJiaBidPrice].Visible = true;
    }

    private string getSubmit()
    {
        Db db = new Db();

        string _strSubmit = "";
        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];

        string strSql = "select max(Submit) as Submit  from V_Bargaining  where   accountid_tb=" + _Account.AccountId;
        System.Data.IDataReader dr = db.DataReader(strSql);
        if (dr.Read())
        {
            _strSubmit = SysFun.ToTrim(dr["Submit"]);
        }
        dr.Close();
        dr.Dispose();
        db.Close();
        return _strSubmit;
    }
    protected void Button3_Click(object sender, EventArgs e) //提交意见
    {
        string strSql = "", strBidY = "";
        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
        foreach (string strId in SysFun.ToTrim(Request.Form["GoodsId"]).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
        {
            if (SysFun.ToInt(Request.Form["radBid" + strId]) == 1)
                strBidY = strBidY + strId + ",";

        }
        Db db = new Db();

        if (strBidY != "")
        {
            strBidY = strBidY.Substring(0, strBidY.Length - 1);
            //strSql = "update V_Bargaining set isbid=1 where goodsid in  (" + strBidY + ") "; // 同意 中标
            //db.Command(strSql);
            strSql = "update V_Bargaining set Accept_Company = 1 where goodsid in  (" + strBidY + "); ";
            strSql += "update V_Bargaining set isbid=1,bidprice=expertprice" + getSubmit() + " where goodsid in  (" + strBidY + ") ";
            db.Command(strSql);
            db.Close();
            HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "修改", "Bargaining", strSql, "../Expert/companyyijia.aspx");
        }
        db.Close();

        //查询
        showGridView();
        //绑定字段
        RowDataBound();
        ////判断提交状态,来觉得提交按钮是否显示

        SelectSubmit();
    }
}
